#include"threadpool.hh"
#include<memory>
#include<chrono>
ThreadPool::ThreadPool(int threadnum,int capa)
    :_threadnum(threadnum)
    ,_isexit(false)
    ,_quesize(capa)
     ,_que(capa)
{}

ThreadPool::~ThreadPool()
{}

void ThreadPool::addTask(funcp& rhs)
{
    if(rhs)
    {
    _que.push(rhs);
    }
}

void ThreadPool::entry()
{
    for(int i=0;i<_threadnum;++i)
    {
        _thread.push_back(std::thread(&ThreadPool::doTask,this));
    }
}

void ThreadPool::exit()
{

    while(!_que.isempty())
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    _isexit=true;
    _que.wakeup();

    for(auto & i:_thread )
    {
        i.join();
    }
    /* for(int i=0;i<_threadnum;++i) */
    /* { */
    /*     _thread[i].join(); */
    /* } */
}
funcp ThreadPool::getTask()
{
    funcp pt = _que.pop();
    if(pt)
    {
        return pt;
    }
    else
    {
        perror("get task wrong");
        return pt;
    }
}

void ThreadPool::doTask()
{
    while(!_isexit)
    {
        funcp task= getTask();
        if(task)
        {
            task();
        }
        else
        {
            perror(" task==nullptr");
        }
    }
}

